<?php

namespace exphp;

class  FileOperations
{
    public static $fileType = '';

    private static function init($path, $mode)
    {
        if (self::$fileType == '') {
            self::$fileType = pathinfo($path)['extension'] ?? '';
        }
        $path = DataTypeConvert::replaceString(['..p/' => PathOperations::getProjectPath($path)], $path);
        PathOperations::VerifyPath($path, $mode);
        return $path;
    }

    /**
     * 将文件读入数组
     * @param string $path 文件路径[..p/代表拼接项目完整路径]
     * @return void
     */
    public static function readFileToArray($path)
    {
        $path = self::init($path, 'rc');
        $fileContent = file_get_contents($path);
        if (self::$fileType == 'json' || self::$fileType == 'xml') {
            $contentArray = DataTypeConvert::convertToArray($fileContent == '' ? array() : $fileContent);
        } elseif (self::$fileType == 'txt' || self::$fileType == 'log') {
            $contentArray = DataTypeConvert::convertToArray($fileContent == '' ? array() : $fileContent, PHP_EOL);
        }
        return isset($contentArray) ? $contentArray : array();
    }

    /**
     * 修改文件,目前支持json|xml
     * @param string $path 修改文件的路径
     * @param array $array 修改内容 [key => value]
     * key表示修改文件的键名 例：a.b.c 代表数组中fiel[a][b][c] 代表xml中的 <fiel><a><b><c></c></b></a></fiel>
     * value表示要修改的内容，存在直接覆盖，支持string|array,其他格式会自动转换成文件关联的json或者xml格式
     * @return void
     */
    public static function modifyFile($path, $upData)
    {
        $path = self::init($path, 'wc');
        $content = self::readFileToArray($path);
        if (self::$fileType != 'json' && self::$fileType != 'xml') {
            OutPut::errorMessage('format nonsupport', '文件修改仅支持json|xml');
        }
        foreach ($upData as $key => $value) {
            $keys = DataTypeConvert::convertToArray($key, '.');
            $param = 'content_';
            $$param = $content;
            $content = &$$param;
            foreach ($keys as $k) {
                $newParam = $param . $k;
                if (isset($$param[$k])) {
                    $$newParam = $$param[$k];
                } else {
                    $$newParam = array();
                }
                $$param[$k] = &$$newParam;
                $param = $newParam;
            }
            $keys = DataTypeConvert::convertToString($keys, '');
            $keys = 'content_' . $keys;
            $$keys = $value;
        }
        return self::writeFile($path, $content);
    }

    /**
     * 写入文件
     * @param string $path 写入路径
     * @param array|string $content 写入内容
     * @return void
     */
    public static function writeFile($path, $content)
    {
        $path = self::init($path, 'wc');
        if (self::$fileType == 'txt' || self::$fileType == 'log') {
            $content = DataTypeConvert::convertToString($content, PHP_EOL);
        } elseif (self::$fileType == 'json') {
            $content = DataTypeConvert::convertToJson($content, true);
        } elseif (self::$fileType == 'xml') {
            $content = DataTypeConvert::convertToXml($content);
        }
        return file_put_contents($path, $content);
    }

    /**
     * 追加写入文件
     * @param string $path 写入路径
     * @param array|string $content 写入内容
     * @return void
     */
    public static function addToWriteFile($path, $content)
    {
        $path = self::init($path, 'wc');
        $content = self::readFileToArray($path);
        if (self::$fileType != 'txt' && self::$fileType != 'txt') {
            OutPut::errorMessage('format nonsupport', '追加写入仅支持txt|log');
        }
        $content[] = $content;
        return self::writeFile($path, $content);
    }

    /**
     * 网页下载
     * @param string $filename 文件命名
     * @param string $filepath 下载文件位置
     * @return void
     */
    public static function webDownlaod($filename, $filepath)
    {
        $filepath = self::init($filepath, 'rc');
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename='{$filename}'");
        header('Content-Transfer-Encoding: binary');
        readfile($filepath);
        exit();
    }
}
